<template>
  <div>
    <!--行内表单    -->
    <el-form :inline="true">
      <el-form-item>
        <el-input
            v-model="searchForm.mandarin"
            placeholder="普通话翻译"
            clearable
        >
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getAudioList">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveHandle">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-popconfirm title="确定批量删除吗？" @confirm="delHandle(null)">
          <el-button type="danger" slot="reference" :disabled="delBtlStatu">批量删除</el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>
    <!--表格-->
    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border
        stripe
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>

      <el-table-column
          prop="mandarin"
          label="普通话翻译"
          width="120">
      </el-table-column>
      <el-table-column
          prop="hakka"
          label="普通话音译"
          show-overflow-tooltip>
      </el-table-column>
      <el-table-column
          prop="hakkaPronunciation"
          label="音频"
          show-overflow-tooltip>
      </el-table-column>
      <el-table-column
          prop="place"
          label="地区"
          show-overflow-tooltip>
      </el-table-column>

      <el-table-column
          prop="icon"
          label="操作">

        <template slot-scope="scope">
          <el-button type="text" @click="editHandle(scope.row.id)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>

          <template>
            <el-popconfirm title="这是一段内容确定删除吗？" @confirm="delHandle(scope.row.id)">
              <el-button type="text" slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <!--分页导航-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 10, 20, 50]"
        :current-page="current"
        :page-size="size"
        :total="total">
    </el-pagination>

    <!--新增对话框-->
    <el-dialog
        :close-on-click-modal=false
        title=""
        :visible.sync="dialogVisible"
        width="600px"
        :before-close="handleClose"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="100px" class="demo-editForm">
        <el-form-item label="普通话翻译" prop="mandarin" label-width="100px">
          <el-input v-model="editForm.mandarin" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="普通话音译" prop="hakka" label-width="100px">
          <el-input v-model="editForm.hakka" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item id="ShowOrHide" v-model="showEl" v-if="showEl===true" label="音频文件" label-width="100px">
          <el-upload
              class="upload-import"
              ref="uploadImport"
              action=""
              accept=".mp3"
              :http-request="httpRequest"
              :auto-upload="false"
              :file-list="fileList"
              :on-remove="handleRemove"
              :on-change="handleChange"
              :before-upload="beforeUpload"
              :limit="1"
              :on-exceed="handleExceed">
            <el-button v-show="!hasFile" slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传mp3文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="地区" prop="place" label-width="100px">
          <el-input v-model="editForm.place" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm()">确定</el-button>
          <el-button @click="resetForm('editForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>

export default {
  name: "Audio",
  data() {
    return {
      //是否展示音频上传，新增展示，修改不展示
      showEl:false,
      hasFile: false,
      fileList: [],
      searchForm: {},
      delBtlStatu: true,
      total: 0,
      size: 5,
      current: 1,
      dialogVisible: false,
      editForm: {},
      tableData: [],
      editFormRules: {
        mandarin: [
          {required: true, message: '请输入普通话翻译', trigger: 'blur'}
        ],
        place: [
          {required: true, message: '请输入地区', trigger: 'blur'}
        ]
      },
      multipleSelection: [],
      permDialogVisible: false,
      permForm: {},
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      permTreeData: []
    }
  },
  created() {
    this.getAudioList()
  },
  methods: {
    handleRemove(file, fileList) {
      if (!fileList.length) {
        this.hasFile = false;
      }
      this.editForm.file = null;
    },
    handleChange(file, fileList) {
      if (fileList.length >= 2) {
        return;
      }
      if (fileList.length === 1) {
        this.hasFile = true;
      }
      this.editForm.file = file;
    },
    beforeUpload(file){
      var testmsg = file.name.substring(file.name.lastIndexOf('.')+1)
      const extension = testmsg === 'mp3'
      if(!extension) {
        this.$message({
          message: '您上传的文件格式不符合要求!只支持mp3格式的文件',
          type: 'warning'
        });
      }
      return extension;
    },
    handleExceed() {
      this.$message.warning(`只能上传1个文件`);
    },
    /*处理勾选状态*/
    handleSelectionChange(val) {
      /*console.log("勾选")
      console.log(val)*/
      this.multipleSelection = val;

      this.delBtlStatu = val.length === 0
    },
    handleSizeChange(val) {
      /*console.log(`每页 ${val} 条`);*/
      this.size = val
      this.getAudioList()
    },
    handleCurrentChange(val) {
      /*console.log(`当前页: ${val}`);*/
      this.current = val
      this.getAudioList()
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.editForm = {};
      this.fileList = [];
      this.hasFile=false;
    },
    handleClose() {
      this.resetForm('editForm')
      this.dialogVisible = false
    },
    getAudioList() {
      this.$axios.get("/sys/audio/list", {
        params: {
          mandarin: this.searchForm.mandarin,
          current: this.current,
          size: this.size
        }
      }).then(res => {
        /*console.log(res)*/
        this.tableData = res.data.data.records
        this.size = res.data.data.size
        this.current = res.data.data.current
        this.total = res.data.data.total
      })
    },
    //确定按钮
    //调用组件upload的submit方法，从而触发httpRequest方法，实现手动上传
    submitForm() {
      if (this.hasFile === false){
        this.$message({
          message: '请上传文件',
          type: 'warning'
        });
      }
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          if(this.editForm.id){
            /*修改*/
            let fd = new FormData();
            fd.append("id", this.editForm.id)
            fd.append('mandarin',  this.editForm.mandarin);
            if (this.editForm.hakka){
              fd.append('hakka',  this.editForm.hakka);
            }
            fd.append('place',  this.editForm.place);
            this.saveOrUpdate(fd);
          }else {
            /*新增*/
            this.$refs.uploadImport.submit();
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    /*自定义上传行为*/
    httpRequest(param) {
      let fd = new FormData();
      fd.append('mandarin',  this.editForm.mandarin);
      fd.append("file", param.file);
      if (this.editForm.hakka){
        fd.append('hakka',  this.editForm.hakka);
      }
      fd.append('place',  this.editForm.place);
      this.saveOrUpdate(fd);
    },
    saveOrUpdate(fd){
      this.$axios.post('/sys/audio/' + (this.editForm.id?'update':'save'), fd , {
        headers: {'Content-Type': 'multipart/form-data'}, //定义内容格式,很重要
        timeout: 20000,
      }).then(res => {
        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success'
        });
        this.getAudioList()
        this.resetForm('editForm')
        this.dialogVisible = false
      })
    },
    saveHandle(){
      this.showEl=true;
      this.dialogVisible = true
    },
    editHandle(id) {
      this.$axios.get('/sys/audio/info/' + id).then(res => {
        this.showEl=false;
        this.editForm = res.data.data
        this.hasFile=true
        this.dialogVisible = true
      })
    },
    delHandle(id) {
      var ids = []
      if (id) {
        ids.push(id)
      } else {
        /*批量删除*/
        this.multipleSelection.forEach(row => {
          ids.push(row.id)
        })
      }
      console.log(ids)
      this.$axios.post("/sys/audio/delete", ids).then(res => {
        this.$message({
          showClose: true,
          message: '删除成功',
          type: 'success'
        });
        this.getAudioList()
      })
    }
  }
}
</script>

<style scoped>
.el-pagination {
  float: right;
  margin-top: 22px;
}
</style>
